'''
Created on 06/08/2010

@author: eh01
'''
from datastore.uri import Uri
from runtime.service import Service
from datastore.spaces import Spaces
from datastore.resource import Resource

class LoggerService(Service):
    
    def cb_start(self, uri, action, res):
        self.spaces.set_process(Uri('internal:base/services/logger/logs/'), self.cb_save_logs)
        self.spaces.set_process(Uri('internal:base/services/logger/logs'), self.cb_get_logs)
        
    def cb_save_logs(self, uri, action, res):
        if action == Spaces.ACTION_PUT:
            for entry in res.log_entries:
                log_id = self.save_log_entry(entry[0], commit=True)
            # don't think anyone would be interested in the ids. So not returning them
            return None
        elif action == Spaces.ACTION_EXISTS:
            return False
        else:
            pass
    
    def cb_get_logs(self, uri, action, res):
        if action == Spaces.ACTION_GET:
            entries_list = self.datastore.get_n_logs(n=50, desc=True)
            rs = Resource(type="term:base/services/logger/logs")
            rs.log_entries = entries_list
            return rs
        elif action == Spaces.ACTION_EXISTS:
            return True
        else:
            pass
        
    def save_log_entry(self, message, commit):
        log_id = self.datastore.log(message, commit=commit)
        return log_id